package com.snk.kof.common.result;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.snk.kof.common.enums.CommonResultEnum;
import com.snk.kof.common.enums.ResultCode;
import com.snk.kof.common.exception.BusinessException;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
import lombok.experimental.FieldDefaults;

import java.io.Serializable;
import java.time.Instant;

/**
 * @author keshan
 * @date 2022-01-02 下午3:10
 */
@Data
@Accessors(chain = true)
@FieldDefaults(level = AccessLevel.PRIVATE)
@NoArgsConstructor(access = AccessLevel.PRIVATE)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Result<T> implements Serializable {

    private static final long serialVersionUID = 6889898770747356222L;

    int code = CommonResultEnum.SUCCESS.getCode();

    String message = CommonResultEnum.SUCCESS.getMessage();

    T data;

    long timestamp = Instant.now().toEpochMilli();

    public static <T> Result<T> success() {
        return new Result<>();
    }

    public static <T> Result<T> success(T data) {
        return new Result<T>().setData(data);
    }

    public static <T> Result<T> error() {
        return new Result<T>()
                .setCode(CommonResultEnum.FAIL.getCode())
                .setMessage(CommonResultEnum.FAIL.getMessage());
    }

    public static <T> Result<T> error(String message) {
        return new Result<T>()
                .setCode(CommonResultEnum.FAIL.getCode())
                .setMessage(message);
    }

    public static <T> Result<T> error(int code, String message) {
        return new Result<T>()
                .setCode(code)
                .setMessage(message);
    }

    public static <T> Result<T> error(ResultCode resultCode) {
        return new Result<T>()
                .setCode(resultCode.getCode())
                .setMessage(resultCode.getMessage());
    }

    public static <T> Result<T> error(BusinessException businessException) {
        return new Result<T>()
                .setCode(businessException.getCode())
                .setMessage(businessException.getMessage());
    }

}
